﻿using CloudMusic.Helper;
using CloudMusic.Model;
using CloudMusic.ViewModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CloudMusic.UC
{
    /// <summary>
    /// UCLrc.xaml 的交互逻辑
    /// </summary>
    public partial class UCLrc : UserControl
    {

        public UCLrc()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LrcView_Loaded(object sender, RoutedEventArgs e)
        {
            MainWindowViewModel.LrcEvent += MusicViewModelBase_LrcEvent;
            MainWindowViewModel.RollEvent += MainWindowViewModel_RollEvent;
        }
        #region 变量
        //歌词集合
        public Dictionary<double, LrcModel> Lrcs;
        //当前焦点所在歌词集合位置
        public LrcModel foucslrc { get; set; }
        //非焦点歌词颜色
        public SolidColorBrush NoramlLrcColor = new SolidColorBrush(Colors.Black);
        //焦点歌词颜色
        public SolidColorBrush FoucsLrcColor = new SolidColorBrush(Colors.OrangeRed);
        private int version = 1;
        long userId;
        #endregion

        #region 加载歌词
        private void MusicViewModelBase_LrcEvent(object sender, EventArgs e)
        {
            try
            {
                contributor.Visibility = Visibility.Collapsed;
                lrcEdit.Visibility = Visibility.Collapsed;
                nullLrc.Visibility = Visibility.Collapsed;
                //用于排序
                List<listLrc> vs = new List<listLrc>();
                //只获取[]里面的内容正则表达式
                var pattern = @"\[(.*?)\]";
                if (c_lrc_items.Children.Count > 0)
                {
                    c_lrc_items.Children.RemoveRange(0, c_lrc_items.Children.Count);
                }
                Lrcs = new Dictionary<double, LrcModel>(new RepeatDictionaryComparer());
                if ((long)sender > 0)
                {
                    // var list = CommonHelper.GetEquipList<LrcRootModel>(1, "http://localhost:3000/lyric?id=" + (long)sender);
                    var strJson = CommonHelper.Get("http://localhost:3000/lyric?id=" + (long)sender);
                    JObject strList = (JObject)JsonConvert.DeserializeObject(strJson);
                    if (strList.ContainsKey("lyricUser"))
                    {
                        if (strList.ToString().Length > 0)
                        {
                            LyricUser UserList = JsonConvert.DeserializeObject<LyricUser>(strList["lyricUser"].ToString());
                            contributorName.Content = UserList.nickname.ToString();
                            userId = UserList.id;
                            contributor.Visibility = Visibility.Visible;
                        }
                    }
                    if (strList.ContainsKey("lrc"))
                    {
                        Lrc list = JsonConvert.DeserializeObject<Lrc>(strList["lrc"].ToString());
                        version = list.version;
                        if (list.lyric != null)
                        {
                            var lrcList = list.lyric.Split('\n');
                            if (list.version == 3)
                            {
                                lrcEdit.Visibility = Visibility.Visible;
                                foreach (string str in lrcList)
                                {
                                    //过滤空行，判断是否存在时间
                                    if (str.Length > 0)
                                    {
                                        //歌词显示textblock控件
                                        TextBlock c_lrcbk = new TextBlock();
                                        //赋值
                                        c_lrcbk.FontSize = 16;
                                        c_lrcbk.Text = str.Trim();
                                        c_lrcbk.LineHeight = 20;
                                        if (c_lrc_items.Children.Count > 0)
                                        {
                                            //增加一些行间距，不那么拥挤
                                            c_lrcbk.Margin = new Thickness(0, 10, 0, 0);
                                        }
                                        //将歌词显示textblock控件添加到界面中显示
                                        c_lrc_items.Children.Add(c_lrcbk);
                                    }
                                }
                            }
                            else
                            {
                                //循环封装歌词
                                foreach (string lrcItem in lrcList)
                                {
                                    //分割-以防万一歌词格式为[xx:xx][xx:xx]等连续格式
                                    string[] strTimes = lrcItem.Split(']');
                                    //把歌词封装在临时的LIST
                                    foreach (string items in strTimes)
                                    {
                                        TextBlock t = new TextBlock();
                                        string itemss = items + "]";
                                        var matches = Regex.Matches(itemss, pattern);
                                        foreach (Match m in matches)
                                        {
                                            vs.Add(new listLrc()
                                            {
                                                LrcText = strTimes[strTimes.Length - 1].ToString(),
                                                Time = "[" + m.Groups[1].ToString() + "]"
                                            });
                                        }
                                    }
                                }
                                //对临时list里面的数据进行排序

                                vs = vs.OrderBy(q => q.Time).ToList();
                                //将歌词发布在页面上
                                for (int i = 0; i < vs.Count; i++)
                                {
                                    TimeSpan time = GetTime(vs[i].Time);
                                    //歌词显示textblock控件
                                    TextBlock c_lrcbk = new TextBlock();
                                    //赋值
                                    c_lrcbk.FontSize = 16;
                                    c_lrcbk.Text = vs[i].LrcText.Trim();
                                    c_lrcbk.LineHeight = 18;
                                    if (c_lrc_items.Children.Count > 0)
                                    {
                                        //增加一些行间距，不那么拥挤
                                        c_lrcbk.Margin = new Thickness(0, 10, 0, 0);
                                    }
                                    //添加到集合，方便日后操作
                                    Lrcs.Add(time.TotalMilliseconds, new LrcModel()
                                    {
                                        c_LrcTb = c_lrcbk,
                                        LrcText = vs[i].LrcText.Trim(),
                                        Time = time.TotalMilliseconds
                                    });
                                    //将歌词显示textblock控件添加控件
                                    c_lrc_items.Children.Add(c_lrcbk);
                                }
                            }
                        }
                        else
                        {
                            nullLrc.Visibility = Visibility.Visible;
                        }
                    }
                    else
                    {
                        nullLrc.Visibility = Visibility.Visible;
                    }

                }
            }
            catch (Exception ex)
            {
                string ss =  ex.Message;
            }
        }

        //正则表达式提取时间
        public TimeSpan GetTime(string str)
        {
            Regex reg = new Regex(@"\[(?<time>.*)\]", RegexOptions.IgnoreCase);
            string timestr = reg.Match(str).Groups["time"].Value;
            //判断是否有小数点
            int s = 0, f = 0;
            //获得分
            int m = Convert.ToInt32(timestr.Split(':')[0]);
            try
            {
                if (timestr.Split(':')[1].IndexOf(".") != -1)
                {
                    //有
                    s = Convert.ToInt32(timestr.Split(':')[1].Split('.')[0]);
                    //获得毫秒位
                    f = Convert.ToInt32(timestr.Split(':')[1].Split('.')[1]);

                }
                else
                {
                    //没有
                    s = Convert.ToInt32(timestr.Split(':')[1]);

                }
                //Debug.WriteLine(m + "-" + s + "-" + f + "->" + new TimeSpan(0, 0, m, s, f).TotalMilliseconds);               
            }
            catch (Exception) { }

            return new TimeSpan(0, 0, m, s, f);
        }

        #endregion

        #region 歌词滚动

        //计算时间差
        public double DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            double dateDiff = 0;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan t = ts1 - ts2;
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                dateDiff = t.Seconds + t.Milliseconds;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return dateDiff;
        }
        #endregion

        #region 歌词滚动
        private void MainWindowViewModel_RollEvent(object sender, EventArgs e)
        {
            try
            {
                if (version == 3 || version == 0) return;
                if (c_lrc_items.Children.Count > 0)
                {
                    var nowtime = (double)sender;
                    if (foucslrc == null)
                    {
                        foucslrc = Lrcs.Values.First();
                        foucslrc.c_LrcTb.Foreground = FoucsLrcColor;
                    }
                    else
                    {
                        //查找焦点歌词
                        IEnumerable<KeyValuePair<double, LrcModel>> s = Lrcs.Where(m => nowtime >= m.Key);
                        if (s.Count() > 0)
                        {
                            LrcModel lm = s.Last().Value;
                            foucslrc.c_LrcTb.Foreground = NoramlLrcColor;
                            foucslrc = lm;
                            foucslrc.c_LrcTb.Foreground = FoucsLrcColor;
                            //定位歌词在控件中间区域
                            ResetLrcviewScroll();
                        }
                    }
                }
            }
            catch (Exception) { }
        }
        #endregion

        #region 调整歌词控件滚动条位置
        public void ResetLrcviewScroll()
        {
            try
            {
                //获得焦点歌词位置
                GeneralTransform gf = foucslrc.c_LrcTb.TransformToVisual(c_lrc_items);
                Point p = gf.Transform(new Point(0, 0));
                //滚动条当前位置
                //Debug.WriteLine(c_scrollviewer.VerticalOffset + "/" + p.Y);

                //计算滚动位置（p.Y是焦点歌词控件(c_LrcTb)相对于父级控件c_lrc_items(StackPanel)的位置）
                //拿焦点歌词位置减去滚动区域控件高度除以2的值得到的【大概】就是歌词焦点在滚动区域控件的位置
                double os = p.Y - (c_scrollviewer.ActualHeight / 2) + 18;
                //滚动
                c_scrollviewer.ScrollToVerticalOffset(os);
            }
            catch (Exception) { }

        }
        #endregion

        private void askScrolling_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("1");
        }

        private void contributorName_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("2");
        }
    }
}
/// <summary>
/// 解决相同键时候的问题
/// </summary>
public class RepeatDictionaryComparer : IEqualityComparer<double>
{
    public bool Equals(double x, double y)
    {
        return x != y;
    }
    public int GetHashCode(double obj)
    {
        return obj.GetHashCode();
    }
}
